import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { getToken } from '../../../components/common/PateoForm/utils/helper';
import moment from 'moment';
import PropTypes from 'prop-types';
import '@ant-design/compatible/assets/index.css';
import { Modal, Button, Table, message, Form, Card, Row, Col } from 'antd';
import styles from '../../../components/common/PateoTable/TableList.less';
import MaskText from '@/components/MaskText';
import { fingerprintFetch } from '@/utils/request'

const mapStateToProps = (state: any) => ({
  user: state?.menu?.userProfile,
});
class LogModal extends PureComponent<any, any> {
  static contextTypes = {
    userProfile: PropTypes.any,
  };
  constructor(props: any) {
    super(props);
    this.state = {
      typeList: [
        {
          value: 0,
          label: '锁车',
        },
        {
          value: 1,
          label: '解除锁车',
        },
        {
          value: 2,
          label: '车机告警',
        },
        {
          value: 3,
          label: '解除车机告警',
        },
      ],
      loading: false,
      exportLoading: false,
      list: [],
      pagination: {},
    };
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  componentDidUpdate(prevProps: any) {
    const { vehicleVin, modalVisible, dispatch } = this.props;

    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      this.setState({ loading: true });
      const params = {
        vin: vehicleVin,
        pageNo: 1,
        pageSize: 10,
      };
      dispatch({
        type: 'http/postDataWithRes',
        payload: {
          url: '/commodity/vehicle/monitor/operateRecord/page',
          ...params,
        },
        callback: (res: any) => {
          /* res: {
            data:{
              pagination: {
                current: 1, pageSize: 10
              },
              rows: [],
              total: '',
            }
            statusCode: "0"   
            statusMessage: "请求成功."
          } */
          const {
            data: { pagination, rows, total },
          } = res;
          if (res.statusCode === '0') {
            this.setState({
              loading: false,
              pagination: {
                ...pagination,
                total,
              },
              list: rows,
            });
          } else {
            message.error('获取操作记录列表失败');
            this.setState({ loading: false });
          }
        },
      });
    }
  }

  queryData = () => {};

  handleDownloadLog = () => {
    const { dispatch, vehicleVin, user } = this.props;
    this.setState({ exportLoading: true });
    dispatch({
      type: 'http/postDataWithRes',
      payload: {
        url: '/commodity/vehicle/monitor/operateRecord/export',
        vin: vehicleVin,
        operator: user?.accountName,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('导出成功');
        }
        this.setState({ exportLoading: false });
      },
    });
  };

  /* handleDownloadLog = () => {
    const { vehicleWin, user } = this.props
    // const { formValues } = this.state;
    // console.log(window.g.url, formValues)
    // const formValues = {
    //   vin: vehicleWin,
    //   operator: user?.accountName,
    // }
    const formValues = {}
    const { pagination } = this.state
    if (pagination.total > 10000 || pagination.total === 0) {
      message.warning('您目前搜索的结果等于0条或者大于10000条，请选择查询条件，精确查询范围！');
      return;
    }
    this.setState({ exportLoading: true })
    // const str = `${window.g.url}/newFeedback/findListToExport`;
    //  commodity/vehicle/monitor/ operateRecord /export
    const str = `${window.g.url}/commodity/vehicle/monitor/operateRecord/export?vin=${vehicleWin}&operator=${user?.accountName}`;
    const newOptions: any = {};
    const obj = Object.assign({}, formValues);
    newOptions.method = 'POST';
    newOptions.body = JSON.stringify(obj);
    newOptions.headers = {
      OptAuthorization: `${getToken()}`,
      'Content-Type': 'application/json;charset=utf-8',
    };
    fingerprintFetch(str, newOptions)
      .then(response => {
        this.setState({
          exportLoading: false,
        });
        if (response.status === 200) {
          return response.blob();
        } else {
          throw response;
        }
      })
      .then(blob => {
        // this.setState({ exportLoading: false })
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `操作记录列表${new Date().toLocaleDateString()}.xls`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      })
      .catch(() => {
        this.setState({
          exportLoading: false,
        });
        message.error('导出失败，请稍后再试!');
      });
  } */

  handleChange = (pagination, filters, sorter, extra) => {
    // console.log(pagination, filters, sorter, extra)
    const { dispatch, vehicleVin, extraHandle = false, currentName = 'pageNo' } = this.props;
    // const current = extraHandle ? pagination.current : pagination.current - 1;
    const params = {
      vin: vehicleVin,
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
    };

    dispatch({
      type: 'http/postDataWithRes',
      payload: {
        url: '/commodity/vehicle/monitor/operateRecord/page',
        ...params,
      },
      callback: (res: any) => {
        const {
          data: { pagination, rows, total },
        } = res;
        if (res.statusCode === '0') {
          this.setState({
            loading: false,
            pagination: {
              ...pagination,
              total,
            },
            list: rows,
          });
        } else {
          message.error('获取操作记录列表失败');
          this.setState({ loading: false });
        }
      },
    });
  };

  close = () => {
    const { closeModal } = this.props;
    closeModal();
  };

  render() {
    // const { modalVisible, loading, detailData } = this.props;
    const { modalVisible } = this.props;
    const { list, loading, pagination, typeList, exportLoading } = this.state;
    const columns = [
      {
        title: '操作类型',
        dataIndex: 'operateType',
        render: (text: any) => {
          let tempStr = '';
          typeList.some((v: any) => {
            const state = v.value == text;
            if (state) {
              tempStr = v.label;
            }
            return state;
          });
          return tempStr;
        },
      },
      {
        title: '操作人员',
        dataIndex: 'createBy',
        render(val: any) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: '操作时间',
        dataIndex: 'createTime',
        // render: (text: any) => moment(text).format('YYYY-MM-DD HH:mm:ss')
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      rowKey: (record: any) => record.sid,
      dataSource: list,
      loading,
      pagination: paginationProps,
      // rowSelection,
      // selectedRowKeys,
      scroll: { x: 'max-content' },
    };
    let tabWidth = 0;
    for (let i in columns) {
      if (columns[i].width) {
        tabWidth += columns[i].width;
      }
    }
    return (
      <Modal
        title="操作记录"
        // style={{ width: '800px' }}
        width={800}
        bodyStyle={{ maxHeight: '700px' }}
        footer={null}
        visible={modalVisible}
        onCancel={this.close}
      >
        <div>
          <Button
            style={{ marginBottom: 8, marginRight: 8 }}
            type={'primary'}
            loading={exportLoading}
            onClick={() => {
              this.handleDownloadLog();
            }}
          >
            导出记录
          </Button>
        </div>
        <div className={styles.standardTable}>
          <Table
            onChange={this.handleChange}
            scroll={{ x: tabWidth }}
            className={styles.my_table}
            size="small"
            {...tableProps}
          />
        </div>
      </Modal>
    );
  }
}

export default connect(mapStateToProps)(LogModal);
